import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs';
import { getUserOpinidAndToken, setUserOpinidAndToken, setSessionUserInfo } from '../util/userInfo';
import { UserAuthService } from './../data/user-auth.service';

@Injectable({
	providedIn: 'root'
})
export class AuthGuard implements CanActivate {
	private firstInit = true;
	constructor(private userAuthService: UserAuthService, private router: Router) {};
	canActivate(
		next: ActivatedRouteSnapshot,
		state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
		return this.checkLogin();
	}
	async checkLogin() {
		const loginUser = getUserOpinidAndToken();
		if (!loginUser.token) {
			// 登录
			await this.userAuthService.login(loginUser).toPromise().then(response => {
				setUserOpinidAndToken(loginUser.openId, response.token);
				setSessionUserInfo(response);
			})
		}
		if (this.firstInit) {
			this.router.navigateByUrl('/task');
			this.firstInit = false;
		}
		return !!loginUser.token;
	}
}
